<template>
    <BasicLayout>
        <template #wrapper>
            <el-card class="box-card">
                <template v-if="userId === -1">
                    <el-form
                        ref="queryForm"
                        :model="queryParams"
                        :inline="true"
                        label-width="100px"
                    >
                        <!--                    <el-form-item label="用户昵称" prop="nickname">-->
                        <!--                        <el-input v-model="queryParams.nickname" placeholder="请输入用户昵称" clearable size="small" @keyup.enter.native="handleQuery" />-->
                        <!--                    </el-form-item>-->
                        <el-form-item label="用户姓名" prop="userName">
                            <el-input
                                v-model="queryParams.userName"
                                placeholder="请输入用户姓名"
                                clearable
                                size="small"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="手机号码" prop="phone">
                            <el-input
                                v-model="queryParams.phone"
                                placeholder="请输入手机号码"
                                clearable
                                size="small"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="支付宝账号" prop="aliPay">
                            <el-input
                                v-model="queryParams.aliPay"
                                placeholder="请输入支付宝账号"
                                clearable
                                size="small"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="订单状态" prop="orderStatus">
                            <el-select
                                v-model="queryParams.orderStatus"
                                placeholder="用户订单表订单状态"
                                clearable
                                size="small"
                            >
                                <el-option
                                    v-for="dict in orderStatusOptions"
                                    :key="dict.dictValue"
                                    :label="dict.dictLabel"
                                    :value="dict.dictValue"
                                />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="订单时间" prop="recordAt">
                            <el-date-picker
                                v-model="queryParams.recordAt"
                                type="date"
                                placeholder="选择日期"
                            >
                            </el-date-picker>
                        </el-form-item>

                        <el-form-item label="店铺名称" prop="shopName">
                            <el-input
                                v-model="queryParams.shopName"
                                placeholder="请输入店铺名称"
                                clearable
                                size="small"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>

                        <el-form-item label="店铺省市" prop="area">
                            <el-cascader
                                v-model="queryParams.area"
                                :options="areaList"
                                clearable
                                :props="{
                                    value: 'name',
                                    label: 'name',
                                    children: 'districts',
                                }"
                            ></el-cascader>
                        </el-form-item>

                        <el-form-item>
                            <el-button
                                type="primary"
                                icon="el-icon-search"
                                size="mini"
                                @click="handleQuery"
                                >搜索</el-button
                            >
                            <el-button
                                icon="el-icon-refresh"
                                size="mini"
                                @click="resetQuery"
                                >重置</el-button
                            >
                        </el-form-item>
                    </el-form>

                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button
                                v-permisaction="['platform:order:add']"
                                type="primary"
                                icon="el-icon-plus"
                                size="mini"
                                @click="handleAdd"
                                >新增</el-button
                            >
                        </el-col>
                        <el-col :span="1.5">
                            <el-button
                                v-permisaction="['platform:order:edit']"
                                type="success"
                                icon="el-icon-edit"
                                size="mini"
                                :disabled="single"
                                @click="handleUpdate"
                                >修改</el-button
                            >
                        </el-col>
                        <el-col :span="1.5">
                            <el-button
                                v-permisaction="['platform:order:remove']"
                                type="danger"
                                icon="el-icon-delete"
                                size="mini"
                                :disabled="multiple"
                                @click="handleDelete"
                            >
                                删除
                            </el-button>
                        </el-col>
                    </el-row>
                </template>
                <el-table
                    v-loading="loading"
                    :data="bworderList"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                    />
                    <el-table-column
                        label="用户"
                        align="center"
                        prop="userName"
                        width="150"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <div class="row ali_cen" style="width: 100%">
                                <el-image
                                    style="
                                        width: 48px;
                                        height: 48px;
                                        border-radius: 48px;
                                        margin-right: 10px;
                                    "
                                    :src="scope.row.avatar"
                                />
                                <span style="flex: 1; text-align: left">{{
                                    scope.row.userName
                                }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="店铺"
                        align="center"
                        prop="nickname"
                        width="150"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <div class="row ali_cen" style="width: 100%">
                                <el-image
                                    style="
                                        width: 48px;
                                        height: 48px;
                                        border-radius: 48px;
                                        margin-right: 10px;
                                    "
                                    :src="scope.row.shopCover"
                                />
                                <span style="flex: 1; text-align: left">{{
                                    scope.row.shopName
                                }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="店铺地址"
                        width="150"
                        align="center"
                        prop="shopAddress"
                    >
                        <template slot-scope="scope">
                            <span>{{
                                scope.row.shopAddress.replaceAll(" ", "")
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="手机号"
                        align="center"
                        prop="phone"
                        width="110"
                    />
                    <el-table-column
                        label="支付宝"
                        align="center"
                        prop="aliPay"
                        width="120"
                    />
                    <el-table-column
                        label="订单金额"
                        align="center"
                        prop="totalPrice"
                        width="80"
                    />
                    <el-table-column
                        label="返还金额"
                        align="center"
                        prop="returnPrice"
                        width="80"
                    />
                    <el-table-column
                        label="订单备注"
                        align="center"
                        prop="remark"
                        :show-overflow-tooltip="true"
                    />
                    <el-table-column
                        label="延时时间"
                        align="center"
                        prop="delayTime"
                        width="120"
                        class-name="small-padding fixed-width bgf8"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.delayTime || 0 }}分钟
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="订单状态"
                        align="center"
                        prop="orderStatus"
                        :formatter="orderStatusFormat"
                        width="100"
                        class-name="small-padding fixed-width bgf8"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            {{ orderStatusFormat(scope.row) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        class-name="small-padding fixed-width bgf8"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <el-button
                                v-permisaction="['platform:order:auth']"
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleUpdate(scope.row)"
                                >修改</el-button
                            >
                            <el-button
                                v-permisaction="['platform:order:auth']"
                                size="mini"
                                type="text"
                                icon="el-icon-position"
                                @click="handleVerify(scope.row)"
                                :disabled="
                                    ![2, 4].includes(scope.row.orderStatus)
                                "
                                v-if="scope.row.orderStatus !== 3"
                            >
                                审核
                            </el-button>
                            <el-button
                                v-else
                                v-permisaction="['platform:order:auth']"
                                size="mini"
                                type="text"
                                icon="el-icon-position"
                                @click="turnDownOrder(scope.row)"
                            >
                                驳回
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageIndex"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
                />

                <!-- 添加或修改对话框 -->
                <el-dialog :title="title" :visible.sync="open" width="90vw">
                    <el-form
                        ref="form"
                        :model="form"
                        :rules="rules"
                        label-width="100px"
                    >
                        <el-form-item label="店铺名称" prop="shopName"
                            ><el-input
                                disabled
                                v-model="form.shopName"
                                placeholder="门店id"
                        /></el-form-item>
                        <el-form-item label="用户名称" prop="userName"
                            ><el-input
                                disabled
                                v-model="form.userName"
                                placeholder="用户id"
                        /></el-form-item>
                        <el-form-item label="外卖订单号" prop="orderSn"
                            ><el-input
                                disabled
                                v-model="form.orderSn"
                                placeholder="外卖订单号"
                        /></el-form-item>
                        <el-form-item label="优惠券" prop="couponId">
                            <div v-if="form.shopCoupon">
                                满{{ form.shopCoupon.useMinMoney }}返{{
                                    form.shopCoupon.returnMoney
                                }}元
                            </div>
                        </el-form-item>
                        <el-form-item label="订单总金额" prop="totalPrice"
                            ><el-input
                                disabled
                                v-model="form.totalPrice"
                                placeholder="订单总金额"
                        /></el-form-item>
                        <!--   <el-form-item label="订单状态" prop="orderStatus"><el-input v-model="form.orderStatus" placeholder="订单状态" /></el-form-item> -->
                        <el-form-item label="手机号码" prop="phone"
                            ><el-input
                                disabled
                                v-model="form.phone"
                                placeholder="手机号码"
                        /></el-form-item>
                        
                         <el-form-item label="优惠券类型" prop="couponType">
                            <div v-if="form.shopCoupon">
                                <span>{{
                                    form.shopCoupon.couponType === 2
                                        ? "美团"
                                        : "饿了么"
                                }}</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="活动时间" prop="">
                            <el-input
                                v-if="form.shopCoupon"
                                readonly
                                :value="
                                    form.shopCoupon.startDate +
                                    ' 到 ' +
                                    form.shopCoupon.endDate
                                "
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="每天时段" prop="">
                            <el-input
                                v-if="form.shopCoupon"
                                readonly
                                :value="
                                    form.shopCoupon.startTime +
                                    ' 到 ' +
                                    form.shopCoupon.endTime
                                "
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="下单时间" prop="">
                            <el-input
                                readonly
                                :value="form.recordAt"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="店铺要求" prop="shopClaim">
                            <el-input
                                style="width: 100%"
                                type="textarea"
                                :value="
                                    form.shopCoupon && form.shopCoupon.shopClaim
                                "
                                readonly
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="返还金额" prop="returnPrice"
                            ><el-input-number
                                :disabled="isEdit"
                                v-model="form.returnPrice"
                                placeholder="返还金额"
                        /></el-form-item>

                        <el-form-item label="审核备注" prop="remark">
                            <el-autocomplete
                                style="width: 100%"
                                class="inline-input"
                                type="textarea"
                                v-model="form.remark"
                                :fetch-suggestions="querySearch"
                                placeholder="审核备注"
                                @select="handleSelect"
                                value-key="reason"
                            ></el-autocomplete>
                        </el-form-item>
                        <el-form-item label="延时时间" prop="delayTime">
                            <div style="display: flex; align-items: center">
                                <el-input-number
                                    :min="0"
                                    v-model="form.delayTime"
                                    placeholder="延时时间"
                                />
                                <span style="margin-left: 10px">分钟</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="订单状态" prop="orderStatus">
                            <el-radio-group
                                v-if="isVerify"
                                v-model="form.orderStatus"
                            >
                                <el-radio :label="3">通过</el-radio>
                                <el-radio :label="4">不通过</el-radio>
                            </el-radio-group>
                            <el-select
                                disabled
                                v-else
                                v-model="form.orderStatus"
                                placeholder="用户订单表订单状态"
                                clearable
                                size="small"
                            >
                                <el-option
                                    v-for="dict in orderStatusOptions"
                                    :key="dict.dictValue"
                                    :label="dict.dictLabel"
                                    :value="Number(dict.dictValue)"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="订单图片" prop="imageList">
                            <div
                                style="
                                    width: 100%;
                                    overflow-x: auto;
                                    white-space: nowrap;
                                "
                            >
                                <el-image
                                    v-for="(item, index) in form.imageList ||
                                    []"
                                    :key="index"
                                    style="
                                        width: 300px;
                                        height: 300px;
                                        border-radius: 10px;
                                        margin-right: 10px;
                                        border: 1px solid #f1f1f1;
                                    "
                                    :src="item.imageUrl"
                                    :preview-src-list="srcList"
                                ></el-image>
                            </div>
                        </el-form-item>
                        <!-- <el-form-item label="记录时间" prop="recordAt">
                            <el-date-picker v-model="form.recordAt" type="datetime" placeholder="选择日期"></el-date-picker>
                        </el-form-item> -->
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm"
                            >确定</el-button
                        >
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </template>
    </BasicLayout>
</template>

<script>
import {
    addBwOrder,
    delBwOrder,
    getBwOrder,
    listBwOrder,
    updateBwOrder,
    turnDownOrder,
} from "@/api/bw/platform/order/order";
import { listBwReason } from "@/api/bw/platform/reason/index";
import { getAreaData } from "@/api/bw/platform/shop/shop";

export default {
    name: "Config",
    props: {
        userId: {
            type: [Number, String],
            default: -1,
        },
        shopId: {
            type: [Number, String],
            default: -1,
        },
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            isEdit: false,
            isVerify: false,
            // 类型数据字典
            typeOptions: [],
            bworderList: [],
            orderStatusOptions: [],
            // 查询参数
            queryParams: {
                pageIndex: 1,
                pageSize: 10,
                totalPrice: undefined,
                returnPrice: undefined,
                orderStatus: undefined,
                phone: undefined,
                area: [],
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                // totalPrice: [{ required: true, message: '订单总金额不能为空', trigger: 'blur' }],
                returnPrice: [
                    {
                        required: true,
                        message: "返还金额不能为空",
                        trigger: "blur",
                    },
                ],
                orderStatus: [
                    {
                        required: true,
                        message: "订单状态不能为空",
                        trigger: "blur",
                    },
                ],
                // phone: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }]
            },
            reasonList: [],
            areaList: [],
        };
    },
    computed: {
        srcList() {
            return (this.form.imageList || []).map((item) => {
                return item.imageUrl;
            });
        },
    },
    created() {
        this.getList();
        this.getDicts("order_status").then((response) => {
            this.orderStatusOptions = response.data;
        });
        listBwReason({
            pageIndex: 1,
            pageSize: 150,
            classId: 1,
        }).then((res) => {
            this.reasonList = res.data.list || [];
        });
        getAreaData().then((res) => {
            this.areaList = res.data || [];
        });
    },
    methods: {
        turnDownOrder(row) {
            this.$confirm("是否驳回该订单", "警告", {
                type: "warning",
            })
                .then(() => {
                    let temp = { ...row };
                    temp.recordAt = temp.recordAt.split(" ")[0];
                    turnDownOrder(row.orderId, temp).then((res) => {
                        if (res.code === 200) {
                            this.getList();
                            this.$message.success("驳回成功");
                        } else {
                            this.$message.success(res.msg);
                        }
                    });
                })
                .catch(function () {});
        },
        querySearch(queryString, cb) {
            cb(
                this.reasonList
            );
        },
        handleSelect() {},
        /** 查询参数列表 */
        getList() {
            this.loading = true;
            let data = this.addDateRange(this.queryParams, this.dateRange);
            if (this.userId !== -1) {
                data.userId = this.userId;
            }
            if (this.shopId !== -1) {
                data.shopId = this.shopId;
            }

            if (data.area.length) {
                data = { ...data };
                data.area = data.area.slice(0);
                data.province = data.area[0];
                data.city = data.area[1];
                delete data.area;
            }
            listBwOrder(data).then((response) => {
                this.bworderList = response.data.list;
                this.total = response.data.count;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                orderId: undefined,
                shopId: undefined,
                userId: undefined,
                orderSn: undefined,
                couponId: undefined,
                totalPrice: undefined,
                returnPrice: undefined,
                orderStatus: undefined,
                phone: undefined,
                remark: undefined,
                recordAt: undefined,
                delayTime: undefined,
            };
            this.resetForm("form");
        },
        orderStatusFormat(row) {
            return this.selectDictLabel(
                this.orderStatusOptions,
                row.orderStatus
            );
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageIndex = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加用户订单表";
            this.isEdit = false;
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.orderId);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const orderId = row.orderId || this.ids;
            getBwOrder(orderId).then((response) => {
                this.form = response.data;
                this.open = true;
                this.title = "订单详情";
                this.isEdit = true;
                this.isVerify = false;
            });
        },
        handleVerify(row) {
            this.reset();
            const orderId = row.orderId || this.ids;
            getBwOrder(orderId).then((response) => {
                response.data.orderStatus = 3;
                this.form = response.data;
                this.open = true;
                this.title = "订单审核";
                this.isEdit = false;
                this.isVerify = true;
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.orderId !== undefined) {
                        let temp = { ...this.form };
                        temp.recordAt = temp.recordAt.split(" ")[0];
                        updateBwOrder(this.form.orderId, temp).then(
                            (response) => {
                                if (response.code === 200) {
                                    this.msgSuccess(
                                        (this.isEdit ? "修改" : "审核") + "成功"
                                    );
                                    this.open = false;
                                    this.getList();
                                } else {
                                    this.msgError(response.msg);
                                }
                            }
                        );
                    } else {
                        addBwOrder(this.form).then((response) => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            } else {
                                this.msgError(response.msg);
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const Ids = row.orderId || this.ids;
            this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(function () {
                    return delBwOrder(Ids);
                })
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                })
                .catch(function () {});
        },
    },
};
</script>
